<template>
  <div class="map">
    <h2 class="text-center">{{ title }}</h2>
    <!-- <div class="amap-page-container">
      <el-amap
        vid="amapDemo"
        :center="center"
        :map-manager="amapManager"
        :zoom="zoom"
        :events="events"
        class="amap-demo"
      ></el-amap>
    </div>-->
    <el-amap
      vid="amapDemo"
      :center="center"
      :zoom="zoom"
      class="amap-demo"
      :events="events"
    ></el-amap>
    <div class="toolbar">
      position: [{{ lng }}, {{ lat }}] address: {{ address }},个人location:{{
        location
      }}
    </div>
  </div>
</template>

<script>
import location from "../../utils/positionLocation.js";
export default {
  name: "map-demo",
  data() {
    let self = this;
    return {
      title: "map",
      zoom: 12,
      center: [120.011574, 30.286369],
      address: "",
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            // console.log(status, result);
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                console.log(result);
                self.address = result.regeocode.formattedAddress;
                self.$nextTick();
              }
            }
          });
        }
      },
      lng: 0,
      lat: 0,
      location: ""
    };
  },
  components: {},
  mounted() {
    this.getLocation();
  },
  methods: {
    getLocation() {
      let _that = this;
      let geolocation = location.initMap("map-container"); // 定位
      AMap.event.addListener(geolocation, "complete", result => {
        console.log(result);
        let { lng, lat } = result.position;
        _that.lat = result.position.lat;
        _that.lng = result.position.lng;
        _that.location = result.formattedAddress;

        var geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
        geocoder.getAddress([lng, lat], function(status, result) {
          console.log(status, result);
          if (status === "complete" && result.info === "OK") {
            if (result && result.regeocode) {
              console.log(result);
              // self.address = result.regeocode.formattedAddress;
              // self.$nextTick();
            }
          }
        });
      });
    }
  }
};
</script>

<style scoped>
.amap-demo {
  height: 300px;
  width: 375px;
  margin: 0 auto;
}
</style>
